import axios from 'axios';

// 获取CSRF令牌
function getCookie(name: string) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

const api = axios.create({
    baseURL: '/api',
    withCredentials: true
});

// 添加请求拦截器
api.interceptors.request.use(
    (config) => {
        // 获取CSRF令牌并添加到请求头
        const csrftoken = getCookie('csrftoken');
        if (csrftoken) {
            config.headers['X-CSRFToken'] = csrftoken;
        }
        console.log('Request:', config.method?.toUpperCase(), config.url, config.data);
        return config;
    },
    (error) => {
        console.error('Request Error:', error);
        return Promise.reject(error);
    }
);

// 添加响应拦截器
api.interceptors.response.use(
    (response) => {
        console.log('Response:', response.status, response.data);
        return response;
    },
    (error) => {
        console.error('Response Error:', error.response?.status, error.response?.data);
        return Promise.reject(error);
    }
);

export interface RegisterData {
    username: string;
    password: string;
    first_name: string;
    email?: string;
    last_name?: string;
}

export interface LoginForm {
    username: string;
    password: string;
}

export interface LoginResponse {
    status: string;
    message?: string;
    user?: any;
    token?: string;
    refreshToken?: string;
}

export const auth = {
    register: async (data: RegisterData) => {
        try {
            const response = await api.post('/auth/register/', data);
            return response.data;
        } catch (error) {
            console.error('Register Error:', error);
            throw error;
        }
    },

    async login(data: LoginForm): Promise<LoginResponse> {
        try {
            const response = await api.post('/auth/login/', data);
            return response.data;
        } catch (error: any) {
            throw error;
        }
    },

    async logout(): Promise<void> {
        try {
            await api.post('/auth/logout/');
        } catch (error: any) {
            throw error;
        }
    },

    async refreshToken(refreshToken: string): Promise<LoginResponse> {
        try {
            const response = await api.post('/auth/refresh-token/', { refreshToken });
            return response.data;
        } catch (error: any) {
            throw error;
        }
    },

    getProfile: async () => {
        try {
            const response = await api.get('/auth/profile/');
            return response.data;
        } catch (error) {
            console.error('Get Profile Error:', error);
            throw error;
        }
    }
}; 